package io.demo.message.serial;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.channels.IllegalSelectorException;

public class JacksonSerializedObject<T> extends SerializedObject<T> {

  private ObjectMapper objectMapper;

  JacksonSerializedObject(T object) {
    super(object);
  }

  @Override
  protected void beforeSerialize() {
    objectMapper = new ObjectMapper();
  }

  @Override
  protected byte[] doSerialization(T object) {
    try {
      return objectMapper.writeValueAsBytes(object);
    } catch (JsonProcessingException e) {
      throw new IllegalArgumentException(e);
    }
  }

  @Override
  public T reverse() {
    @SuppressWarnings("unchecked")
    Class<T> cc = (Class<T>) getObjectClass();
    try {
      return objectMapper.readValue(getByteArray(), cc);
    } catch (IOException e) {
      throw new IllegalSelectorException();
    }
  }
}
